import { BookList, Book, User } from '../models';

export default function (router) {
  /**
   * 前端获取阅读记录
   */
  router.get('/api/front/booklist', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const thisBookList = await BookList.findOne({ userid }).populate({
      path: 'books.bookid',
      options: {
        select: 'name author img_url update_status update_time newest_chapter'
      }
    });
    await ctx.json(true, '获取书单信息成功', thisBookList || []);
  });

  /**
   * 前端添加阅读记录
   */
  router.post('/api/front/booklist/add', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const { id } = ctx.request.body;
    if (!id) {
      await ctx.json(false, '缺少id参数');
      return false;
    }

    const hisBookList = await BookList.findOne({ userid });
    const hasInitBookList = hisBookList && hisBookList.books instanceof Array;
    const isExisted = hasInitBookList ? hisBookList.books.some(book => book.bookid.toString() === id) : false;
    if (isExisted) {
      await ctx.json(false, '书籍已经在书架中');
    } else {
      const updateResult = await BookList.updateOne(
        { userid },
        {
          $addToSet: {
            books: {
              bookid: ctx.transId(id),
              rss: 0,
              time: new Date(),
              read: { num: 1, top: 0 }
            }
          }
        }
      );
      if (updateResult.ok === 1) {
        await ctx.json(true, '添加书籍到书架成功');
      } else {
        await ctx.json(false, '添加书籍到书架失败');
      }
    }
  });

  /**
   * 前端订阅书籍
   */
  router.post('/api/front/booklist/rss', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { bookid, rss } = ctx.request.body;
    const { userid } = ctx.state.user;
    const thisBook = await Book.findById(bookid, '_id');
    if (!thisBook) {
      ctx.body = { ok: false, msg: '找不到此书籍' };
      return false;
    }
    const updateResult = await BookList.updateOne(
      {
        userid: userid,
        'books.bookid': bookid
      },
      { $set: { 'books.$.rss': rss == '1' ? 1 : 0 } }
    );
    if (updateResult.ok === 1) {
      ctx.body = { ok: true, msg: '修改书籍订阅状态成功' };
    } else {
      ctx.body = { ok: false, msg: '修改书籍订阅状态失败' };
    }
  });

  /**
   * 更新用户阅读进度接口
   */
  router.put('/api/front/booklist/update', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    if (!userid) {
      await ctx.noLogin();
      next();
      return;
    }
    const { bookid, chapter_num, chapter_page_index = 0, chapter_page_top = 0, read_time = 0 } = ctx.request.body;

    // 校验参数合法性
    if (!(bookid && chapter_num && (chapter_page_index || chapter_page_index == 0) && (chapter_page_top || chapter_page_top == 0))) {
      await ctx.json(false, '参数错误');
      return false;
    }

    // 校验booklist
    const thisBookList = await BookList.findOne({ userid });
    if (!thisBookList) {
      await ctx.json(false, '用户未初始化阅读记录');
      return false;
    }

    // 检查当前书籍是否加入到了书架中
    const theBookList = await BookList.findOne({ userid, 'books.bookid': bookid });
    if (!theBookList && bookid) {
      // 默认将其加入书架
      const addBookResult = await BookList.updateOne(
        { userid },
        {
          $addToSet: {
            books: {
              bookid: ctx.transId(bookid),
              rss: 0,
              time: new Date(),
              read: { num: 1, top: 0 }
            }
          }
        }
      );

      if (addBookResult.ok !== 1) {
        await ctx.json(false, '加入阅读记录失败');
        return false;
      }
    }

    // 开始更新
    const updateResult = await BookList.updateOne(
      {
        userid,
        'books.bookid': bookid
      },
      {
        $set: {
          'books.$.read': {
            num: chapter_num,
            top: chapter_page_index || 0,
            scroll: chapter_page_top || 0
          },
          'books.$.time': new Date()
        }
      }
    );

    const updateReadTime = await User.updateOne({ _id: userid }, { $inc: { read_time: parseInt(read_time) } });
    if (updateResult.ok === 1 && updateReadTime.ok === 1) {
      if (updateResult.nModified === 1) {
        await ctx.json(true, `更新阅读进度成功，最新进度第${chapter_num}章节`);
      } else {
        await ctx.json(true, '阅读进度没有改动');
      }
    } else {
      await ctx.json(true, '更新阅读进度失败');
    }
  });

  /**
   * 前端删除阅读记录
   */
  router.post('/api/front/booklist/remove', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;

    const { id } = ctx.request.body;
    if (!id) {
      await ctx.json(false, '缺少id参数');
      return false;
    }

    const updateResult = await BookList.updateOne({ userid: userid }, { $pull: { books: { bookid: id } } });
    if (updateResult.ok === 1) {
      await ctx.json(true, '删除书籍成功');
    } else {
      await ctx.json(false, '删除书籍失败');
    }
  });
}
